package cn.gjxblog.controller;


import cn.gjxblog.api.AgencyServerFegin;
import cn.gjxblog.api.CommentServerFegin;
import cn.gjxblog.api.FileServiceFegin;
import cn.gjxblog.api.HouseServerFegin;
import cn.gjxblog.common.model.HttpResult;
import cn.gjxblog.common.model.PageCondition;
import cn.gjxblog.common.model.PageData;
import cn.gjxblog.model.*;
import cn.gjxblog.model.dto.CommentDTO;
import cn.gjxblog.model.dto.HouseQueryDTO;
import cn.gjxblog.model.entity.*;
import cn.gjxblog.model.vo.CommentVO;
import cn.gjxblog.model.vo.HouseVO;

import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * @author gjx
 * @version v1.0
 * @Description
 * @date 2018/12/12 10:31
 */
@Controller
@RequestMapping("/house")
public class HouseController {


    @Resource
    private FileServiceFegin fileServiceFegin;


    @Autowired
    private HouseServerFegin houseServerFegin;

    @Autowired
    private AgencyServerFegin agencyServerFegin;

    @Autowired
    private CommentServerFegin commentServerFegin;

    @RequestMapping(value = "/list",method={RequestMethod.POST,RequestMethod.GET})
    public String houseList(PageCondition pageCondition, House house, Model model) {
        pageCondition.setPageSize(6);
        HouseQueryDTO houseQueryDTO = new HouseQueryDTO();
        houseQueryDTO.setPageCondition(pageCondition);
        houseQueryDTO.setHouse(house);

        HttpResult<PageInfo<HouseVO>> pageInfoHttpResult = houseServerFegin.searchHouses(houseQueryDTO);
        PageInfo<HouseVO> result = pageInfoHttpResult.getResult();
        PageData<HouseVO> ps = PageData.buildPage(result.getList(), result.getTotal(), pageCondition.getPageSize(), pageCondition.getPageNum());


        //排行榜
        List<HouseVO> rcHouses = queryHotHouses();

        model.addAttribute("recomHouses",rcHouses);
        model.addAttribute("vo",house);
        model.addAttribute("pageCondition",pageCondition);
        model.addAttribute("ps",ps);


        model.addAttribute("count",result.getTotal());

        return "/house/listing";
    }

    @GetMapping(value="/detail")
    public String houseDetail(String id,ModelMap modelMap){
        HttpResult<HouseVO>  restHouse = houseServerFegin.getHouse(id);
        HouseVO house = restHouse.getResult();

        //排行榜
        List<HouseVO> rcHouses = queryHotHouses();

        modelMap.put("agent", agencyServerFegin.getAgent(house.getUserId()).getResult());
        modelMap.put("house", house);
        modelMap.put("recomHouses", rcHouses);

        CommentDTO commentDTO = new CommentDTO();
        commentDTO.setHouseId(id);
        commentDTO.setType(1);
        commentDTO.setSize(8);
        List<CommentVO> comments = commentServerFegin.queryComment(commentDTO).getResult();
        modelMap.put("commentList", comments);
        return "/house/detail";
    }

    /**
     * 获取热度排行榜
     * @return
     */
    private List<HouseVO> queryHotHouses() {
        HttpResult<List<HouseVO>> restHouses = houseServerFegin.queryHotHouses(CommonConstants.RECOM_SIZE);
        List<HouseVO> rcHouses =restHouses.getResult();
        return  rcHouses;
    }

    @PostMapping(value="/leaveMsg")
    public String houseMsg(HouseMsg houseMsg){
        houseServerFegin.addHouseMsg(houseMsg);
        return "redirect:/house/detail?id=" + houseMsg.getHouseId() + "&" +ResultMsg.successMsg("留言成功").asUrlParams();
    }

    @RequestMapping(value="/toAdd",method={RequestMethod.POST,RequestMethod.GET})
    public String toAdd(ModelMap modelMap){
        List<City> citys = houseServerFegin.queryCitys().getResult();
        List<Community> communities = houseServerFegin.queryCommunitys().getResult();

        modelMap.put("citys", citys);
        modelMap.put("communitys", communities );
        return "/house/add";
    }

    @ResponseBody
    @GetMapping(value="/rating")
    public ResultMsg houseRate(Double rating,String id){
        houseServerFegin.houseRate(rating,id);
        return ResultMsg.success();
    }

    @RequestMapping(value="/add",method={RequestMethod.POST,RequestMethod.GET})
    public String doAdd(HouseVO house,MultipartFile[] houseFiles,MultipartFile[] floorPlanFiles,String editorValue){
        house.setRemarks(editorValue);
        if(houseFiles != null){
            HttpResult responseVO = null;
            StringBuffer stringBuffer = new StringBuffer();
            try {
                for (MultipartFile houseFile : houseFiles) {
                    responseVO = fileServiceFegin.upload(houseFile.getBytes(),houseFile.getOriginalFilename());
                    if(responseVO.getResult() != null){
                        stringBuffer.append((String) responseVO.getResult()+",");
                    }
                }
                house.setImages(stringBuffer.toString());//设置封面
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(floorPlanFiles != null){
            HttpResult responseVO = null;
            StringBuffer stringBuffer = new StringBuffer();

            for (MultipartFile floorPlanFile : floorPlanFiles) {
                try {
                    responseVO = fileServiceFegin.upload(floorPlanFile.getBytes(),floorPlanFile.getOriginalFilename());
                    if(responseVO.getResult() != null) {
                        stringBuffer.append((String) responseVO.getResult()+",");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            house.setFloorPlan(stringBuffer.toString());//设置封面
        }
        if(house.getFeatureList().size()>0){
            StringBuffer stringBuffer = new StringBuffer();
            house.getFeatureList().stream().forEach(s->{
                stringBuffer.append(s+",");
            });
            String substring = stringBuffer.substring(0, stringBuffer.length() - 1);
            house.setProperties(substring);
        }

        User user = UserContext.getUser();
        houseServerFegin.addHouse(house,user.getId());
        return "redirect:/house/ownlist?" +ResultMsg.successMsg("添加成功").asUrlParams();
    }



    @RequestMapping(value="/ownlist",method={RequestMethod.POST,RequestMethod.GET})
    public String ownlist(HouseVO house, PageCondition pageCondition, ModelMap modelMap){
        pageCondition.setPageSize(6);
        User user = UserContext.getUser();

        HouseQueryDTO houseQueryDTO = new HouseQueryDTO();
        houseQueryDTO.setUserId(user.getId());
        houseQueryDTO.setBookmarked(false);
        houseQueryDTO.setPageCondition(pageCondition);

        HttpResult<PageInfo<HouseVO>> pageInfoHttpResult = houseServerFegin.queryHousesByUserId(houseQueryDTO);
        PageInfo<HouseVO> result = pageInfoHttpResult.getResult();
        PageData<HouseVO> houseVOPageData = PageData.buildPage(result.getList(), result.getTotal(), pageCondition.getPageSize(), pageCondition.getPageNum());

        modelMap.put("ps",houseVOPageData) ;
        modelMap.put("pageType","own");
        return "/house/ownlist";
    }

    @RequestMapping(value="/del",method={RequestMethod.POST,RequestMethod.GET})
    public String delsale(String id,String pageType){

        if("own".equals(pageType)){
            houseServerFegin.deleteHouse(id);
        }else{
            User user = UserContext.getUser();
            houseServerFegin.collectHouse(id, user.getId(),false);
        }
        return "redirect:/house/ownlist";
    }

    /**
     * 收藏房子
     * @param id
     * @param modelMap
     * @return
     */
    @RequestMapping(value="/bookmark",method={RequestMethod.POST,RequestMethod.GET})
    public String bookmark(String id,ModelMap modelMap){
        User user = UserContext.getUser();
          houseServerFegin.collectHouse(id, user.getId(),true);
       return "redirect:/house/ownlist";
    }

    @RequestMapping(value="/bookmarked",method={RequestMethod.POST,RequestMethod.GET})
    public String bookmarked(HouseVO house,PageCondition pageCondition,ModelMap modelMap){
        User user = UserContext.getUser();

        HouseQueryDTO houseQueryDTO = new HouseQueryDTO();
        houseQueryDTO.setHouse(house);
        houseQueryDTO.setPageCondition(pageCondition);
        houseQueryDTO.setUserId(user.getId());
        houseQueryDTO.setBookmarked(true);

        PageInfo<HouseVO> result = houseServerFegin.queryHousesByUserId(houseQueryDTO).getResult();
        PageData<HouseVO> houseVOPageData = PageData.buildPage(result.getList(), result.getTotal(), pageCondition.getPageSize(), pageCondition.getPageNum());

        modelMap.put("ps", houseVOPageData) ;
        modelMap.put("pageType", "book") ;
        return "/house/ownlist";
    }

    @RequestMapping(value="/unbookmark",method={RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public ResultMsg unbookmark(String id,ModelMap modelMap){
        User user = UserContext.getUser();
        houseServerFegin.collectHouse(id, user.getId(),false);
        return ResultMsg.success();
    }
}
